package cn.itcast.web.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义类型转换器
 *     写一个类，实现Converter接口
 */
@Component
public class StringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        System.out.println("source = " + source);
        try {
            // 判断
            if (StringUtils.isEmpty(source)){
                return null;
            }
            int length = source.toCharArray().length;
            // 转换
            if (length == 10){
                return new SimpleDateFormat("yyyy-MM-dd").parse(source);
            }else if (length == 11){
                return new SimpleDateFormat("yyyy年MM月dd日").parse(source);
            }else
                return null;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
